package com.centanet.framework.utils;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义url的Linkify {@link android.text.util.Linkify}
 * Created by guilin on 16/4/6.
 */
public final class MyUrlLinkify {

    private MyUrlLinkify() {
        //Utility Class
    }

    /**
     * @param textView    TextView
     * @param text        文本
     * @param spanOnClick url点击监听
     */
    public static void addUrlLink(TextView textView, String text, WebClickableSpan.SpanOnClick spanOnClick) {
        if (TextUtils.isEmpty(text)) {
            textView.setText(text);
        } else {
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            SpannableString spannableString = new SpannableString(text.toLowerCase());
            Matcher matcher = Pattern.compile(PatternFormat.HttpUrl).matcher(spannableString);
            while (matcher.find()) {
                String key = matcher.group();
                if (!TextUtils.isEmpty(key)) {
                    spannableString.setSpan(new WebClickableSpan(key, spanOnClick),
                            matcher.start(),
                            matcher.end(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            textView.setText(spannableString);
        }
    }
}
